﻿#include "tabwidget.h"
#include "ui_tabwidget.h"

TabWidget::TabWidget(QWebEngineProfile *profile, QWidget *parent) :
    QTabWidget(parent),
    ui(new Ui::TabWidget),
    m_profile(profile)
{
    ui->setupUi(this);


    // 切换tab
    connect(this, &QTabWidget::currentChanged, this, [=](int idx){
//        qDebug()<<"change tab: idx = "<<idx<<", count = "<<count();
        WebView *view = webView(idx);
        if(view != nullptr){
            QUrl url = view->url();
//            qDebug() << "new url = "<<url;
            emit urlChanged(url);
        }
    });

    // 关闭
    connect(this, &QTabWidget::tabCloseRequested, this, &TabWidget::closeTab);

    // 双击新增标签页
    connect(tabBar(), &QTabBar::tabBarDoubleClicked, [this](int index) {
        if (index == -1)
            createTab();
    });

}

TabWidget::~TabWidget()
{
    delete ui;
}

WebView *TabWidget::currentWebView() const
{
    return qobject_cast<WebView*>(widget(currentIndex()));
}

WebView *TabWidget::webView(int idx) const
{
    if(idx < 0)return nullptr;
    return qobject_cast<WebView *>(widget(idx));
}

void TabWidget::setCurrentWebView(WebView *webView)
{
    setCurrentWidget(webView);
}

void TabWidget::setupView(WebView *webView)
{
    QWebEnginePage *webPage = webView->page();

    // 更新tab对应网页的title
    connect(webView, &QWebEngineView::titleChanged, [this, webView](const QString &title) {
        int index = indexOf(webView);
        if (index != -1) {
            QString _title = title;
            if(_title.length() >  8){
                _title = title.left(8);
            }
            _title += "...";
            setTabText(index, _title);
            setTabToolTip(index, title);
        }
        if (currentIndex() == index)
            emit titleChanged(title);
    });
    // 更新对应页面的头信息（tabData）
    connect(webView, &QWebEngineView::urlChanged, [this, webView](const QUrl &url) {

        int index = indexOf(webView);
        if (index != -1)
            tabBar()->setTabData(index, url);
        if (currentIndex() == index){
            emit urlChanged(url);   // 更新输入栏url
        }
    });
    // 加载中，显示进度
    connect(webView, &QWebEngineView::loadProgress, [this, webView](int progress) {
        if (currentIndex() == indexOf(webView))
            emit loadProgress(progress);
    });

    // 鼠标显示超链接
    connect(webPage, &QWebEnginePage::linkHovered, [this, webView](const QString &url) {
        if (currentIndex() == indexOf(webView))
            emit linkHovered(url);
    });

    // 图标改变
    connect(webView, &WebView::favIconChanged, [this, webView](const QIcon &icon) {
        int index = indexOf(webView);
        if (index != -1)
            setTabIcon(index, icon);
        if (currentIndex() == index)
            emit favIconChanged(icon);
    });

    // 启用某些功能
    connect(webView, &WebView::webActionEnabledChanged, [this, webView](QWebEnginePage::WebAction action, bool enabled) {
        if (currentIndex() ==  indexOf(webView))
            emit webActionEnabledChanged(action,enabled);
    });

    // 检测url是否已经在收藏夹
    connect(webView, &WebView::checkUrlIsMark, [this, webView](){
       emit checkUrlIsMark(webView->url().toString());
    });

    // 请求中止
    connect(webPage, &QWebEnginePage::windowCloseRequested, [this, webView]() {
        int index = indexOf(webView);
        if (index >= 0)
            closeTab(index);
    });

    //
    connect(webView, &WebView::urlChanged, this, [=](QUrl url){
        emit urlChanged(url);
    });

    //
    connect(webView, &WebView::urlNotSafe, this, [=](QString url){
        emit urlNotSafe(url);
    });
}

// 创建新标签页
WebView *TabWidget::createTab()
{
    WebView *view = createBackgroundTab();
    setCurrentWebView(view);
    return view;
}


WebView * TabWidget::createBackgroundTab(){
    WebView * view = new WebView();
    WebPage *page = new WebPage(m_profile, view);
    view->setWebPage(page);
    // 设置view中的处理逻辑
    setupView(view);
    // idx用来设置图标
    int idx = addTab(view, tr("new tab"));
    QIcon icon = view->favIcon();
    setTabIcon(idx, icon);
    return view;
}



void TabWidget::handleIconChanged(int idx, QIcon icon)
{
    if(idx < 0)return;
    setTabIcon(idx, icon);
}

/**
 * @brief TabWidget::closeTab，关闭标签页
 * @param idx
 */
void TabWidget::closeTab(int index)
{
    qDebug()<<"index = "<<index;
    if(count() == 0)return;
    if (WebView *view = webView(index)) {
        bool hasFocus = view->hasFocus();
        removeTab(index);
        if (hasFocus && count() > 0)
            currentWebView()->setFocus();
        if (count() == 0)
            createTab();
        // 资源释放
        view->deleteLater();
    }
}

void TabWidget::removeTab(int idx)
{
    QTabWidget::removeTab(idx);
    if(count() <= 0){
        createTab();
    }
}
